﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PinService.Lib;
using LKVMLMLib;
using LKVService;
using Utility.Date;
using System.Security.Cryptography;
using System.Text;

namespace PinService.Controllers
{
    public class PinController : Controller
    {
        //
        // GET: /Pin/
        public MaThePaymentService PinContext = new MaThePaymentService();
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult GetListCard(int UserId)
        {
            try
            {
                var Pins = PinContext.ListCardByUser(UserId);
                if (Pins.Count() > 0)
                {
                    return Json(new { Result = Pins, Status = true, Messeger = "" });
                }
                return Json(new { Result = "", Status = false, Messeger = "Loading Pins not data" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }
        }
        public ActionResult AddCard(int UserId)
        {
            try
            {
                var Pins = PinContext.ListCardByUser(UserId);
                if (Pins != null)
                {
                    return Json(new { Result = Pins, Status = true, Messeger = "" });
                }
                return Json(new { Result = "", Status = false, Messeger = "Loading Pins not data" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }
        }
        /// <summary>
        /// Get Rate
        /// </summary>
        /// <returns></returns>
        public ActionResult GetPinRate()
        {
            try
            {
                var pinrate = PinContext.GetPinRate();
                if (pinrate != null)
                {
                    return Json(new { Result = pinrate, Status = true, Messeger = "" });
                }
                return Json(new { Result = "", Status = false, Messeger = "Loading Pins not data" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }
        }    
        public ActionResult getListPinByUserId(int userId = 0)
        {
            if (userId == 0)
                return Json(new { Status = false, Result = "", Msg = "No data" });
            var lsPin = PinContext.ListCardByUser(userId).Where(w => w.Used == false).ToList();
            if (lsPin.Count == 0)
                return Json(new { Status = false, Result = "", Msg = "Pin empty" });
            else
                return Json(new { Status = true, Result = lsPin, Msg = "" });
        }
        public ActionResult TransferPin(int pinId = 0, int userTo = 0)
        {
            var kq = PinContext.transferPin(pinId, userTo);
            if (kq.Equals("*"))
                return Json(new { Status = true, Result = "", Msg = "Success !!!" });
            else
                return Json(new { Status = false, Result = "", Msg = kq });
        }
        public ActionResult TransferPinOfQuantum(int userSend = 0, int userRecieve = 0, int Quantum = 0, string password2 = "")
        {
            if (PinContext.checkPasswordLevel2(userSend, MD5Hash(password2)) == false)
                return Json(new { Status = false, Result = "", Msg = "Password 2 wrong" });
            var check = PinContext.countPinOfUser(userSend);
            if (check < Quantum || Quantum == 0)
                return Json(new { Status = false, Result = "", Msg = "Pin is not enough or equal to 0" });
            var kq = PinContext.transferPinOfQuantity(userSend, userRecieve, Quantum);
            if (kq == true)
                return Json(new { Status = true, Result = "", Msg = "Success !!!" });
            else
                return Json(new { Status = false, Result = "", Msg = "Faild !!!" });

        }
        public ActionResult checkCountPin(int userId)
        {
            var kq = PinContext.countPinOfUser(userId);
            if (kq >= 4)
                return Json(new { Status = true, Result = "", Msg = "Success !!!" });
            else
                return Json(new { Status = false, Result = "", Msg = "Fail" });
        }
        public ActionResult getPinOfUser(int userId)
        {
            var kq = PinContext.countPinOfUser(userId);
            if (kq > 0)
                return Json(new { Status = true, Result = kq, Msg = "Success !!!" });
            else
                return Json(new { Status = false, Result = "Building", Msg = "Faild !!!" });
        }
        //lấy pin tạo PH
        public ActionResult getPinForPH(int userId = 0)
        {
            if (userId == 0)
                return Json(new { Status = false, Result = "", Msg = "Faild !!!" });
            var kq = PinContext.getPinEarlyDate(userId);
            if (String.IsNullOrWhiteSpace(kq))
                return Json(new { Status = false, Result = "", Msg = "Faild !!!" });
            else
                return Json(new { Status = true, Result = kq, Msg = "Faild !!!" });
        }
        //Hàm kích pin --> tạo PH & check time kích pin
        public ActionResult pushPin(int userId = 0, string pin = "")
        {
            if (userId == 0 || pin == "")
                return Json(new { Status = false, Result = "", Msg = "Pin not found" });
            var us = PinContext.findUserbyUserId(userId);
            if(us == null)
                return Json(new { Status = false, Result = "", Msg = "User not found" });
            if(us.UserName.Equals("root"))
                return Json(new { Status = false, Result = "", Msg = "Cannot use pin" });
            var kq = PinContext.countPinOfUser(userId);
            if (kq < 1)
                return Json(new { Status = false, Result = "", Msg = "Pin not enough" });
            //kiểm tra xem user có bị khóa
            if(us.IsFirst == false && us.Status != true)
                return Json(new { Status = false, Result = "", Msg = "Your account has been locked, please unlock" });
            var rsp = PinContext.createPH(userId,pin);      
            if(rsp.Equals("***"))
            {
                //check xem có phải lần đầu kích pin
                var rs = PinContext.checkUsedIsFirst(userId);
                if(rs)
                {
                    PinContext.editUserToNotFirst(userId);
                    PinContext.activerUser(userId);
                }              
                PinContext.addMoneyForWalletPublic(userId);
                return Json(new { Status = true, Result = "", Msg = "Success !!! You have to queue PH (Provide Help)" });
            }else
                return Json(new { Status = false, Result = "", Msg = rsp });

        }
        public ActionResult getPinHistory(int userId = 0)
        {
            if(userId == 0)
                return Json(new { Status = false, response = "", Msg = "User not found" },JsonRequestBehavior.AllowGet);
            var ls = PinContext.getPinHistory(userId);
            if(ls.Count == 0)
                return Json(new { Status = false, response = "", Msg = "No data" },JsonRequestBehavior.AllowGet);
            else
                return Json(new { Status = true, response = ls, Msg = "Success" },JsonRequestBehavior.AllowGet);
        }
        //kiểm tra xem user có phải lần đầu đăng ký và chưa kích pin
        public ActionResult checkIsFirstForPin(int userId = 0)
        {
            if(userId == 0)
               return Json(new { Status = false, response = "", Msg = "User not found" });
            var kq = PinContext.checkUsedIsFirst(userId);
            if(!kq)
                return Json(new { Status = false, response = "", Msg = "" });
            else
                return Json(new { Status = true, response = kq, Msg = "Success" });
        }
        // Hàm lấy time chờ kích pin tạo PH
        public ActionResult getTimeWaitActivePinForPH(int userId = 0)
        {
            var times = PinContext.getTimePinUsedNearly(userId);
            //var count = PinContext.countPinOfUser(userId);
            //if(count < 3)
            //{ 
            if(times.TotalDays > 4 && times.TotalDays < 7 )
            {
                // từ ngày thứ 5 sau khi kích pin show thông báo
                var tw = new TimeSpan(7, 0, 0, 0).Subtract(times);
                string ts = (tw.Days > 0 ? tw.Days.ToString() + " days " : "") + (tw.Hours > 0 ? tw.Hours.ToString() + " hours " : "")
                    + (tw.Minutes > 0 ? tw.Minutes.ToString() + " minutes " : "");
                var check = PinContext.countPinOfUser(userId);
                if(check < 2)
                    return Json(new { Status = true,flag = true, Result = "You have only "+ ts +" left to activate pin, place a pending PH order before your account is locked", Msg = "" });
                else
                    return Json(new { Status = false, flag = false, Result = "", Msg = "" });
            }
            else if(times.TotalDays > 7.05)
            {
                // quá 7 ngày thì khóa tài khoản và yêu cầu dùng pin để mở khóa
                //PinContext.lockUser(userId);
                return Json(new { Status = false, flag = true, Result = "Your account has been locked !!!", Msg = "" });
            }
            return Json(new { Status = false, flag = false, Result = "", Msg = "" });
            //}
            //return Json(new { Status = false, flag = false, Result = "", Msg = "" });
        }
        //Hàm mở khóa user
        public ActionResult unlockUser(int userId = 0)
        {
            if (userId == 0)
                return Json(new { Status = false, Result = "", Msg = "User not found" });
            var countPin = PinContext.countPinOfUser(userId);
            if(countPin < 2)
                return Json(new { Status = false, Result = "", Msg = "You need at least 2 pin to unlock" });        
            var at = PinContext.activerUser(userId);
            if(at)
            {
                var kq = PinContext.activePinByQuantum(userId, 2, 1);
                if(kq)
                    return Json(new { Status = true, Result = "", Msg = "Unlock successfully" });
                else
                    return Json(new { Status = false, Result = "", Msg = "Fail !!! * " });
            }
            else
            {
                return Json(new { Status = false, Result = "", Msg = "Fail !!! * " });
            }
        }
        public static string MD5Hash(string text)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(text));
            byte[] result = md5.Hash;
            StringBuilder strBuilder = new StringBuilder();
            for (int i = 0; i < result.Length; i++)
            {
                strBuilder.Append(result[i].ToString("x2"));
            }

            return strBuilder.ToString();
        }
    }
}
